package com.ada.filter;

import org.apache.dubbo.common.utils.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MethodUtil {
    public static ConcurrentHashMap<String, List<MethodInfo>> methodInfos = new ConcurrentHashMap<>();

    public static void record(String method, long during, long end) {
        List<MethodInfo> methodInfoList = methodInfos.get(method);
        MethodInfo methodInfo = new MethodInfo(method, during, end);
        if (methodInfoList == null) {
            methodInfoList = new ArrayList<>();
        }
        methodInfoList.add(methodInfo);
        methodInfos.put(method, methodInfoList);
    }

    public static void show() {
        long currentTime = System.currentTimeMillis();
        long startTime = currentTime - 60 * 1000;
        StringBuilder stringBuilder = new StringBuilder("================================\n");
        stringBuilder.append("当前时间").append(new Date());
        for (Map.Entry<String, List<MethodInfo>> entry : methodInfos.entrySet()) {
            //System.out.println(entry.getKey() + "当前长度" + entry.getValue().size());
            List<MethodInfo> duringMethod = new ArrayList<>();
            for (MethodInfo methodInfo : entry.getValue()) {
                if (methodInfo.getEndTime() >= startTime && methodInfo.getEndTime() <= currentTime) {
                    duringMethod.add(methodInfo);
                }
            }
            CollectionUtils.sort(duringMethod);
            int index90 = duringMethod.size() * 90 / 100;
            int index99 = duringMethod.size() * 99 / 100;
            stringBuilder.append("\n 方法名" + entry.getKey() + " TP90:" + duringMethod.get(index90).getDuringTime() + " TP99:" + duringMethod.get(index99).getDuringTime());
        }
        System.out.println(stringBuilder.toString());
    }
}
